package cn.com.taiji.oospub.wechat.common.helper;


import cn.com.taiji.model.finals.SessionNames;
import cn.com.taiji.oospub.wechat.common.MySessionNames;
import cn.com.taiji.oospub.wechat.entity.MemberBaseInfo;
import cn.com.taiji.pub.SecurityUtil;
import cn.com.taiji.pub.TimeTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;



/**
 * @ClassName: ForegroundLoginHelper.java
 * @Description: 前台登录验证
 * @author zhangxin Email：zhangxinc@mail.taiji.com.cn
 * @date 2013-6-17
 */

public class ForegroundLoginHelper
{
	protected static Logger logger = LoggerFactory.getLogger(ForegroundLoginHelper.class);

	public static boolean hasLogin(HttpServletRequest request)
	{
		MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, MySessionNames.LOGIN_MEMBER);
		return (member != null && StringUtils.hasText(member.getId()));
	}

	public static void setSession(HttpServletRequest request, MemberBaseInfo loginMember)
	{
		Assert.notNull(loginMember);
		String ip = request.getRemoteHost();
		if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
		WebUtils.setSessionAttribute(request, SessionNames.LOGIN_IP, ip);
		WebUtils.setSessionAttribute(request, SessionNames.LOGIN_TIME, TimeTools.toTimeStr());
		WebUtils.setSessionAttribute(request, MySessionNames.LOGIN_MEMBER, loginMember);
		logger.debug("Set session attributes after login:{}", loginMember);
	}

	//20130617 zhangxin 前台登录验证密码
	public static boolean isPassValid(String pass, MemberBaseInfo memberBaseInfo)
	{
		if (memberBaseInfo == null) {
            return false;
        }
		String secPasswd = SecurityUtil.encryptStr(pass, SecurityUtil.HashType.SHA_1, true);
		return secPasswd.equals(memberBaseInfo.getPasswd());
	}
}
